package com.example.ex06;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;

public class SimplePlayerService extends Service{
	public enum STATE{IDLE,STOP,PLAYING,PAUSE};
	private STATE state = STATE.IDLE;
	private MediaPlayer mplayer = new MediaPlayer();
	private final IBinder binder = new SimplePlayerBinder();
	public boolean playOrPause(String music_path){
		if( state == STATE.IDLE ){
			try{
				mplayer.reset();
				mplayer.setDataSource("/sdcard/Adele - Someone Like You.mp3");
				mplayer.prepare();
				mplayer.start();
				state = STATE.PLAYING;
				return true;
			}
			catch(IOException o){}	
		}
		else if( state == STATE.PAUSE ){
			mplayer.start();
			state = STATE.PLAYING;
			return true;
		}
		else if( state == STATE.PLAYING ){
			mplayer.pause();
			state = STATE.PAUSE;
			return false;
		}
		else if( state == STATE.STOP ){
			try {
				mplayer.start();
				state = STATE.PLAYING;
				return true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return false;
	}
	
	public void setCurPos(int pos){
		mplayer.seekTo( mplayer.getDuration() * pos / 100);
	}
	
	public void stop(){
		if( state == STATE.IDLE )
			return ;
		else{
			try {
				mplayer.stop();
				mplayer.prepare();
				state = STATE.STOP;
			
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public int getDuration(){
		if( state == STATE.IDLE )
			return 0;
		else 
			return mplayer.getDuration();
	}
	
	public STATE getCurState(){
		return state;
	}
	public int getCurPos(){
		if( state == STATE.IDLE )
			return 0;
		else
			return mplayer.getCurrentPosition();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return binder;
	}
	
	public class SimplePlayerBinder extends Binder{
		SimplePlayerService getService(){
			return SimplePlayerService.this;
		}
	}
	
}
